#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "my_utils.h"
#include "json.hpp"

int initClient(in_addr_t addr, uint16_t port)
{
    int client;
    struct sockaddr_in client_addr; // 使用结构体 SOCKADDR_IN 存储配置
    client = socket(AF_INET, SOCK_STREAM, 0);

    memset(&client_addr, 0, sizeof(client_addr)); // 清零
    client_addr.sin_family = AF_INET;
    client_addr.sin_addr.s_addr = addr; // server端ip地址
    client_addr.sin_port = port;      // 监听端口

    int res = connect(client, (struct sockaddr *)&client_addr, sizeof(client_addr));

    if (res < 0)
    {
        return -1;
    }
    return client;
}

int main()
{
    // 初始化socket服务端
    uint16_t port = htons(9000);
    in_addr_t addr = inet_addr("192.168.3.112");

    int client = initClient(addr, port);

    while (true)
    {
        // 接收响应数据
        unsigned char recv_buf[1024];
        int len = recv(client, recv_buf, 1024, 0);
        if (len > 0)
        {
            std::string str = byte2String(recv_buf, 0, len);
            std::cout << "[response]: " << str << std::endl;
            nlohmann::json request = nlohmann::json::parse(str);
            std::cout << "[response]: " << request.dump() << std::endl;
        }

        // 发送请求
        unsigned char send_buf[10] = "hello";
        send(client, send_buf, 10, 0);

        sleep(1);
    }
}